package com.example.alpha.campusbase.Activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.SaveCallback;
import com.avos.avoscloud.im.v2.AVIMClient;
import com.avos.avoscloud.im.v2.AVIMException;
import com.avos.avoscloud.im.v2.callback.AVIMClientCallback;
import com.example.alpha.campusbase.Fragment.FeedbackFragment;
import com.example.alpha.campusbase.Fragment.HabitFragment;
import com.example.alpha.campusbase.Fragment.HandlerFragment;
import com.example.alpha.campusbase.Fragment.HomeFragment;
import com.example.alpha.campusbase.Fragment.MessageFragment;
import com.example.alpha.campusbase.Fragment.MineFragment;
import com.example.alpha.campusbase.Interface.BackHandleInterface;
import com.example.alpha.campusbase.R;
import com.example.alpha.campusbase.User;
import com.example.alpha.campusbase.UserLocalStore;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,BackHandleInterface {

    private Menu mMainMenu;
    private UserLocalStore userLocalStore;//用户数据存取器
    private HomeFragment homeFragment;//主页视图
/*    private HabitFragment habitFragment;//俱乐部视图*/
    private HabitFragment habitFragment;
    private MessageFragment messageFragment;//消息视图
    private MineFragment mineFragment;//‘我的’视图
    private FeedbackFragment feedbackFragment;//反馈视图
    private FragmentManager fragmentManager;//碎片管理器
    private FloatingActionButton fab;//浮动按钮
    private Toolbar toolbar;
    private Toolbar toolbar_chat;
    private Fragment fragment;//临时指向需要存放的碎片

    private HandlerFragment mHandlerFragment;
    //private View snakebarView;

    @SuppressLint("CommitTransaction")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //自定义标题栏
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar_chat= (Toolbar) findViewById(R.id.toolbar_chat);
        toolbar_chat.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        toolbar_chat.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        setSupportActionBar(toolbar);

        AVObject testObject = new AVObject("TestObject");
        testObject.put("words","Hello World!");
        testObject.saveInBackground(new SaveCallback() {
            @Override
            public void done(AVException e) {
                if(e == null){
                    Log.d("saved","success!");
                }
            }
        });



        //浮动按钮
        fab = (FloatingActionButton) findViewById(R.id.fab);
        assert fab != null;
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //比Toast更好用的吐司打印工具.但是view寻找困难
                Snackbar.make(view, R.string.notSupport, Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        //侧滑抽屉导航视图
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        if (drawer != null) {
            drawer.setDrawerListener(toggle);
        }
        toggle.syncState();

        //为侧滑菜单绑定点击事件
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        if (navigationView != null) {
            navigationView.setNavigationItemSelectedListener(this);
        }

        //预先初始化各个碎片视图，用于随时切换
        homeFragment=new HomeFragment();
       /* habitFragment=new HabitFragment();*/
        habitFragment=new HabitFragment();
        messageFragment=new MessageFragment();
        mineFragment=new MineFragment();
        feedbackFragment=new FeedbackFragment();

        //获取碎片管理器
        fragmentManager=getSupportFragmentManager();
        //开启碎片操作事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        //初始显示为homefragment
        transaction.replace(R.id.content_frame,homeFragment).commit();

        //实例化用户数据操作器
        userLocalStore=new UserLocalStore(MainActivity.this);


    }

    //在Fragment的onAttach()之后onCreate()之前被调用
    @Override
    public void onAttachFragment(android.app.Fragment fragment) {
        super.onAttachFragment(fragment);
    }

    //在onstart中判断用户是否登陆
    @Override
    protected void onStart() {
        super.onStart();
        if(!authLogin()){
            Intent intent=new Intent(this,LoginActivity.class);
            startActivity(intent);
        }
        else {
            User user=userLocalStore.getLoggenUser();
            //打开动态修改侧滑个人信息
            NavigationView navigationView= (NavigationView) findViewById(R.id.nav_view);
            View headerView = null;
            if (navigationView != null) {
                headerView = navigationView.getHeaderView(0);
            }
            TextView name= null;
            if (headerView != null) {
                name = (TextView) headerView.findViewById(R.id.login_userName);
            }
            TextView email= null;
            if (headerView != null) {
                email = (TextView) headerView .findViewById(R.id.Login_userEmail);
            }
            if (name != null) {
                name.setText(user.name);
            }
            if (email != null) {
                email.setText(user.email);
            }
            if (TextUtils.isEmpty(user.campusname)){
                setTitle(getString(R.string.Home));
            }
            else
                setTitle(user.campusname);
            LogginInternet();
        }
    }

    //获取登陆状态
    private boolean authLogin(){
        return userLocalStore.getUserLoginState();
    }

    //重写返回键事件
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        //如何侧滑拉出则关闭抽屉，否则正常返回
        if (drawer != null) {
            if (drawer.isDrawerOpen(GravityCompat.START)) {
                drawer.closeDrawer(GravityCompat.START);
            }
            else if(getSupportFragmentManager().getBackStackEntryCount()>0){
                getSupportFragmentManager().popBackStack();
                onToolbarchanged(true,null);
            }
            else {
                super.onBackPressed();
            }
        }
    }

    //加载设置菜单，右上角
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mMainMenu=menu;

        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    //菜单项点击事件
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        switch (id){
            case R.id.action_clear:
            case R.id.action_add_at_start:
                //执行homeFragment中接口定义的方法
                homeFragment.executeMethodInFragment(id);
                break;
            case R.id.action_settings:
                Toast.makeText(MainActivity.this,getResources().getString(R.string.notSupport),Toast.LENGTH_SHORT).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //左侧item点击事件
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        //临时存储标题栏标题
        String barTitle=null;
        //临时fragment引用变量
        fragment=null;
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        switch (id){
            case R.id.home_item:
                barTitle=getString(R.string.CampusName);
                fragment=homeFragment;
                break;
            case R.id.message_item:
                barTitle=getString(R.string.Message);
                fragment=messageFragment;
                break;
            case R.id.habit_item:
                barTitle=getString(R.string.Habit);
                fragment=habitFragment;
                break;
            case R.id.mine_item:
                barTitle=getString(R.string.Account);
                fragment=mineFragment;
                break;
            case R.id.share_item:
                barTitle=getString(R.string.Share);
                break;
            case R.id.feedback_itm:
                barTitle=getString(R.string.FeedBack);
                fragment=feedbackFragment;
                break;
        }
        if (fragment!=null){
            //在beginTransaction并且commit后不再需要commit
            fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).commit();
            MenuItem mClear=mMainMenu.findItem(R.id.action_clear);
            MenuItem mAdd=mMainMenu.findItem(R.id.action_add_at_start);
            if (fragment!=homeFragment){
                mClear.setVisible(false);
                mAdd.setVisible(false);
                fab.setVisibility(View.INVISIBLE);
            }
            else {
                mClear.setVisible(true);
                mAdd.setVisible(true);
                fab.setVisibility(View.VISIBLE);
            }
        }
        if(!TextUtils.isEmpty(barTitle)){
            setTitle(barTitle);
        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        //关闭侧滑栏
        assert drawer != null;
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    //设置标题栏标题
    @Override
    public void setTitle(CharSequence title) {
        if (toolbar.isShown()){
            toolbar.setTitle(title);
        }
        else {
            toolbar_chat.setTitle(title);
        }
    }


    @Override
    public void setSelectFragment(HandlerFragment selectFragment) {
        this.mHandlerFragment=selectFragment;
    }

    public void onToolbarchanged(final Boolean mainVisisble, String title){
        if (mainVisisble){
            toolbar_chat.setVisibility(View.GONE);
            toolbar.setVisibility(View.VISIBLE);
            setSupportActionBar(toolbar);
            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    DrawerLayout drawer= (DrawerLayout) findViewById(R.id.drawer_layout);
                    if (drawer != null) {
                        if (!drawer.isDrawerOpen(GravityCompat.START)) {
                            drawer.openDrawer(GravityCompat.START);
                        }
                        else
                            drawer.closeDrawer(GravityCompat.START);
                    }
                }
            });
        }
        else {
            toolbar.setVisibility(View.GONE);
            toolbar_chat.setVisibility(View.VISIBLE);
            toolbar_chat.setTitle(title);
            setSupportActionBar(toolbar_chat);
            //导航按钮的点击事件必须在setSupportActionBar方法的后面绑定
            toolbar_chat.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        }
    }

    public void LogginInternet(){
        //Jerry登录
        AVIMClient gaoyanqiang = AVIMClient.getInstance("Jerry");
        gaoyanqiang.open(new AVIMClientCallback(){

            @Override
            public void done(AVIMClient client,AVIMException e){
                if(e==null){
                    //登录成功后的逻辑
                }
            }
        });
    }

}
